"""
表单模板数据模型
"""
from sqlalchemy import Column, Integer, String, Text, Boolean, DateTime, ForeignKey
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship

from  core.database import Base


class Template(Base):
    """表单模板表"""
    __tablename__ = "templates"
    
    id = Column(Integer, primary_key=True, index=True, comment="模板ID")
    name = Column(String(255), nullable=False, comment="模板名称")
    description = Column(Text, nullable=True, comment="模板描述")
    category = Column(String(100), nullable=True, comment="模板分类")
    latest_version = Column(Integer, nullable=False, default=1, comment="最新版本号")
    is_active = Column(Boolean, nullable=False, default=True, comment="是否激活")
    created_by = Column(Integer, ForeignKey("doctors.id"), nullable=True, comment="创建者ID")
    created_at = Column(
        DateTime(timezone=True),
        nullable=False,
        server_default=func.now(),
        comment="创建时间"
    )
    updated_at = Column(
        DateTime(timezone=True),
        nullable=False,
        server_default=func.now(),
        onupdate=func.now(),
        comment="更新时间"
    )
    version_history = Column(JSONB, nullable=True, comment="版本历史(JSON)")
    
    # 关系
    creator = relationship("Doctor", back_populates="templates")
    
    def __repr__(self):
        return f"<Template(id={self.id}, name={self.name}, version={self.latest_version})>"

